package com.action;

import com.alibaba.fastjson.JSONObject;
import com.bean.ResponseBean;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class UploadAction {

    @Value("${upload.tmp.dir}")
    private String tmp;

    @Value("${upload.dir}")
    private String upload ;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate rt ;

    /**
     * 上传图片
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload")
    public ResponseBean upload(MultipartFile file) throws IOException {

        File tmpFile = new File(tmp);
        if (tmpFile.exists()==false){
            tmpFile.mkdirs();
        }

        File uploadFile = new File(upload);
        if (uploadFile.exists()==false){
            uploadFile.mkdirs();
        }

        //得到原来的文件名  xxxx.jpg
        if(file == null) {
            return ResponseBean.error("0") ;
        }
        String oldFileName = file.getOriginalFilename();
        //得到一个最后一个.的位置
        int index = oldFileName.lastIndexOf('.');
        //得到后辍名
        String extName = oldFileName.substring(index);
        //新的文件名
        String newFileName = System.currentTimeMillis() + extName;
        //file.transferTo(descFile);
        //传到tmp目录
        file.transferTo(new File(tmp + newFileName));
        return new ResponseBean(0,0,newFileName);
    }

    /**
     * 文件上传到临时目录
     * @return
     */
    @RequestMapping("/upload_tmp_dir")
    public ResponseBean upLoadTmpDir(MultipartFile file) throws IOException {
        if (file == null) {
            return new ResponseBean(500, "上传失败", 0);
        }
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        String newFileName = System.currentTimeMillis() + extName;
        File desc = new File(tmp, newFileName);
        if (desc.exists() == false) {
            desc.mkdirs();
        }
        file.transferTo(desc);
        String[] ss = upload.split("/");
        List list = new ArrayList();
        //存储路径
        String root = ss != null && ss.length > 0 ? ss[ss.length - 1] : "";
        //图片名称
        list.add(newFileName);
        //图片路径
        System.out.println("/" + root + "/" + newFileName);
        list.add(( root + "/" + newFileName).replaceAll("\\\\","/"));

        return new ResponseBean(200, "", list);
    }


    @RequestMapping("/upload_bg")
    public ResponseBean uploadBg(MultipartFile file) throws IOException {

        //System.out.println("传过来的文件："+file);
        //得到原来的文件名  xxxx.jpg
        String oldFileName = file.getOriginalFilename();
        //得到一个最后一个.的位置
        int index = oldFileName.lastIndexOf('.');
        //得到后辍名
        String extName = oldFileName.substring(index);
        //新的文件名
        String newFileName = System.currentTimeMillis()+extName;
        //传到tmp目录
        File descFile = new File(upload, newFileName);
        file.transferTo(descFile);

        rt.boundValueOps("wuye:gongpai:bg").set(newFileName);

        //System.out.println("新图片："+newFileName);
        return new ResponseBean(200,0,newFileName);
    }

    @RequestMapping(value="/uploadImage")
    @ResponseBody
    public Object uploadImage(MultipartFile file) {
        String filename = file.getOriginalFilename();
        boolean boole = true;
        String newFileName = "";
        if(file == null) {
            return ResponseBean.error("0") ;
        }
        try{
            String oldFileName = file.getOriginalFilename();
            //得到一个最后一个.的位置
            int index = oldFileName.lastIndexOf('.');
            //得到后辍名
            String extName = oldFileName.substring(index);
            //新的文件名
            newFileName = System.currentTimeMillis() + extName;
            file.transferTo(new File(upload + newFileName));
        }catch (Exception e){
            System.out.println("图片保存异常");
            boole = false;
        }
        if (boole) {
            Map<String,Object> map = new HashMap<String,Object>();
            Map<String,Object> map2 = new HashMap<String,Object>();
            map.put("code", 0);	//0表示上传成功
            map.put("msg","上传成功"); //提示消息
            map2.put("src", "/upload/" + newFileName);
            map2.put("title", newFileName);
            map.put("data", map2);
            return map;
        } else {
            return new ResponseBean(1,1,newFileName);
        }
    }

    /**
     * 文件复制
     * @param srcPath  要复制文件路径
     * @param destPath 复制到那里
     * @param fileName 复制来的文件的名称
     * @return 是否成功
     * @throws IOException
     */
    private static boolean copyFile(String srcPath, String destPath, String fileName) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            File file = new File(srcPath);
            if (!file.exists()) {
                System.out.println("tmp目录不存在");
                return false;
            }
            is = new FileInputStream(file);
            os = new FileOutputStream(new File(destPath, fileName));
            byte[] b = new byte[1024];
            int len = 0;
            while (-1 != (len = is.read(b))) {
                os.write(b, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            return false;
        } finally {
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        }
        return true;
    }

    @PostMapping("/uploadImg")
    @CrossOrigin("*")
    public ResponseBean uploadImg(MultipartFile  file) throws IllegalStateException, IOException{
        //目的地1
        File uploadFile = new File(upload+"images/goods");
        if (uploadFile.exists()==false){
            uploadFile.mkdirs();
        }
        //目的地2  类别图片
        File typeFile = new File(upload+"type");
        if (typeFile.exists()==false){
            typeFile.mkdirs();
        }
        //目的地3  自提点图片
        File zitidianLogo = new File(upload+"images/zitidianLogo");
        if (zitidianLogo.exists()==false){
            zitidianLogo.mkdirs();
        }
        //目的地4  轮播图图片
        File lunbotu = new File(upload+"lunbotu");
        if (lunbotu.exists()==false){
            lunbotu.mkdirs();
        }
        //目的地5  退换货图片
        File refund = new File(upload+"tuiHuanHuoImages");
        if (refund.exists()==false){
            refund.mkdirs();
        }
        //目的地6  用户头像
        File userIcon = new File(upload+"userIcon");
        if (userIcon.exists()==false){
            userIcon.mkdirs();
        }
        //目的地7  店铺图片
        File merchant = new File(upload+"merchant");
        if (merchant.exists()==false){
            merchant.mkdirs();
        }
        //目的地8  评价图片
        File appraise = new File(upload+"appraise");
        if (appraise.exists()==false){
            appraise.mkdirs();
        }
        //目的地9  骑手图片
        File rider = new File(upload+"rider");
        if (rider.exists()==false){
            rider.mkdirs();
        }
        //目的地
        File tmpFile = new File(tmp);
        if (tmpFile.exists()==false){
            tmpFile.mkdirs();
        }

        //得到旧的文件名
        String oldFileName = file.getOriginalFilename();
        //得到原来的后辍名
        int index = oldFileName.lastIndexOf('.');
        int index2=-10;
        if(index<0)
            index2=file.getContentType().lastIndexOf('/');
        String extName="";
        if(index>-1)
            extName = oldFileName.substring(index);
        if(index2>-1)
            extName="."+file.getContentType().substring(index2+1);
        //根据系统时间拼一个当前新的文件名
        String newFileName = System.currentTimeMillis()+extName;
        //目的地
        File descFile = new File(tmp, newFileName);
        file.transferTo(descFile);

        return new ResponseBean(0, "上传成功", newFileName);
    }

    //上传视频的接口
    @RequestMapping(value = "/uploadVideo",method = RequestMethod.POST)
    public Object uploadVideo(@RequestParam("layuiVideo") MultipartFile[] layuiFile, HttpServletRequest request, HttpServletResponse response){
        System.out.println("进入wph的layui视频上传接口》》》》》》》》》》》》》》》");
        Map<String,Object> map=new HashMap<String,Object>();
        Map<String,Object> map2=new HashMap<String,Object>();
        map =kitFileUtil(layuiFile, request, response);
        String error = map.get("error").toString();
        if("101".equals(error)){
            map2.put("error",101);
            map2.put("message",map.get("message"));
            return map;
        }
        map2.put("error",0);
        String url[]=(String[])map.get("url");
        map2.put("url",url[0]);
        return JSONObject.toJSON(map2);
    }

    private static ServletContext servletContext;

    //视频上传的工具方法
    public Map<String,Object> kitFileUtil(@RequestParam("imgFile") MultipartFile[] imgFile, HttpServletRequest request, HttpServletResponse response){

        // 文件保存目录路径
        String savePath = upload+"video/";

        //文件保存目录URL
        String saveUrl  = "upload/video/";

        //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,txt,zip,rar,gz,bz2");

        //最大文件大小
        long maxSize = 9000000;

        response.setContentType("text/html; charset=UTF-8");

        if(!ServletFileUpload.isMultipartContent(request)){
            return getError("请选择文件。");
        }
        //检查目录
        File uploadDir = new File(savePath);
        if(!uploadDir.exists()){
            uploadDir.mkdir();
        }

        //检查目录写权限
        if(!uploadDir.canWrite()){
            return getError("上传目录没有写权限。");
        }

        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "image";
        }
        if(!extMap.containsKey(dirName)){
            return getError("目录名不正确。");
        }

        //创建文件夹
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String url[] = new String[imgFile.length];
        Map<String,Object> map = new HashMap<String, Object>();
        for (int i=0;i<imgFile.length;i++) {
            // 获取上传文件的名字
            String fileName = imgFile[i].getOriginalFilename();
            // 获取长度
            long fileSize = imgFile[i].getSize();

            if(!imgFile[i].isEmpty()){

                // 检查文件大小
                if(imgFile[i].getSize() > maxSize){
                    return getError("上传文件大小超过限制。");
                }

                // 检查扩展名
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
                    return getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try{
                    // 保存文件
                    FileCopyUtils.copy(imgFile[i].getInputStream(), new FileOutputStream(savePath + newFileName));

                }catch(Exception e){
                    return getError("上传文件失败。");
                }
                url[i] = saveUrl + newFileName;
            }
        }
        map.put("error", 0);
        map.put("url", url);
        return map;
    }

    private Map<String,Object> getError(String message) {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("error", 101);
        map.put("message", message);
        return map;
    }
}
